package com.runen.infinitemovement.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.runen.infinitemovement.R;
import com.runen.infinitemovement.activity.ColumnDetailsActivity;
import com.runen.infinitemovement.activity.LoginActivity2;
import com.runen.infinitemovement.adapter.NewColumnAdapter;
import com.runen.infinitemovement.adapter.NewConsultAdapter;
import com.runen.infinitemovement.model.api.ActivityAPI;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.entity.CollageInfoEntity;
import com.runen.infinitemovement.model.entity.EventBusEntity;
import com.runen.infinitemovement.tool.GlideUtils;
import com.runen.infinitemovement.widget.imageview.RoundedCornersImage;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.TimeUtil;
import com.runen.rxnetlibrary.utils.ToastUtils;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.zhouwei.mzbanner.MZBannerView;
import com.zhouwei.mzbanner.holder.MZHolderCreator;
import com.zhouwei.mzbanner.holder.MZViewHolder;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class CollegeFragment extends Fragment {
    @BindView(R.id.mzbView)
    MZBannerView mzbView;
    @BindView(R.id.rvConsultList)
    RecyclerView rvConsultList;
    @BindView(R.id.srl)
    SmartRefreshLayout srl;
    @BindView(R.id.v_line_6dp)
    View vLine6dp;
    private int type;
    private View view;
    private NewColumnAdapter consultAdapter;
    private int page = 1;

    public static Fragment newInstance(int key) {
        Fragment fragment = new CollegeFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("point", key);
        fragment.setArguments(bundle);
        return fragment;
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.frament_news, container, false);
            type = getArguments().getInt("point");
            ButterKnife.bind(this, view);
            initView();
            mzbView.setIndicatorVisible(true);
            initData();
        }
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        mzbView.start();
    }

    @Override
    public void onPause() {
        super.onPause();
        mzbView.pause();
    }

    private void initView() {
        mzbView.setVisibility(View.GONE);
        vLine6dp.setVisibility(View.GONE);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvConsultList.setLayoutManager(layoutManager);
        consultAdapter = new NewColumnAdapter(getActivity());
        rvConsultList.setAdapter(consultAdapter);
        consultAdapter.setOnClick(new NewConsultAdapter.OnClick() {
            @Override
            public void OnItemClick(int position) {
                Intent intent = new Intent(getActivity(), ColumnDetailsActivity.class);
                intent.putExtra("informationId", consultAdapter.getData().get(position).informationId);
                startActivity(intent);
            }
        });
        initRefreshLoadMore();

        rvConsultList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (getActivity() != null) {
                        Glide.with(getActivity()).resumeRequests();//恢复Glide加载图片
                    }
                } else {
                    if (getActivity() != null) {
                        Glide.with(getActivity()).pauseRequests();//禁止Glide加载图片
                    }
                }
            }
        });
    }

    private void initRefreshLoadMore() {
//        srl.autoRefresh();
        srl.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                initData();
            }
        });
        srl.setOnLoadMoreListener(new com.scwang.smart.refresh.layout.listener.OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                loadMore();
            }
        });
    }

    private void initData() {
        String string = "?limit=10&page=1";
        new ActivityAPI().getMyLongCollageInfo(String.format(string, type), new BaseResultCallback<CollageInfoEntity>() {
            @Override
            public void onResponse(CollageInfoEntity response) {
                srl.finishRefresh();
                if (response.code == 0) {
                    if (response.data != null) {
                        if (response.data.bannerList != null && response.data.bannerList.size() > 0) {
                            setView(response.data.bannerList);
                        }
                        if (response.data.informationList != null && response.data.informationList.size() > 0) {
                            consultAdapter.setData(response.data.informationList);
                            if (consultAdapter.getData().size() >= response.data.count) {
                                srl.setEnableLoadMore(false);
                            }
                        }

                    }
                } else {
                    ToastUtils.showShort(response.msg);
                }

            }

            @Override
            public void onError(Throwable e, String body) {
                if (!TextUtils.isEmpty(body)) {
                    if (body.contains("Invalid access token")) {
                        UserAPI.clearLogin();
                        startActivity(new Intent(getActivity(), LoginActivity2.class));
                    }
                }
                super.onError(e, body);
            }
        });
    }

    private void setView(List<CollageInfoEntity.DataBean.BannerListBean> banners) {
        mzbView.setPages(banners, new MZHolderCreator<BannerViewHolder>() {
            @Override
            public BannerViewHolder createViewHolder() {
                return new BannerViewHolder(banners);
            }
        });
        mzbView.addPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    public void loadMore() {
        String string = "?limit=10&page=%s";
        new ActivityAPI().getMyLongCollageInfo(String.format(string, page, type), new BaseResultCallback<CollageInfoEntity>() {
            @Override
            public void onResponse(CollageInfoEntity response) {
                srl.finishLoadMore();
                if (response.code == 0) {
                    if (response.data != null) {
                        if (response.data.informationList != null && response.data.informationList.size() > 0) {
                            consultAdapter.addList(response.data.informationList);
                            if (consultAdapter.getData().size() >= response.data.count) {
                                srl.setEnableLoadMore(false);
                            }
                        }
                    }
                } else {
                    ToastUtils.showShort(response.msg);
                }

            }

            @Override
            public void onError(Throwable e, String body) {
                if (!TextUtils.isEmpty(body)) {
                    if (body.contains("Invalid access token")) {
                        UserAPI.clearLogin();
                        startActivity(new Intent(getActivity(), LoginActivity2.class));
                    }
                }
                super.onError(e, body);
            }
        });
    }

    public static class BannerViewHolder implements MZViewHolder<CollageInfoEntity.DataBean.BannerListBean> {
        private RoundedCornersImage mImageView;
        private RelativeLayout rl_banner;
        private TextView tv_label;
        private TextView tv_time;
        private List<CollageInfoEntity.DataBean.BannerListBean> listString = new ArrayList<>();

        public BannerViewHolder(List<CollageInfoEntity.DataBean.BannerListBean> lists) {
            listString.clear();
            for (int i = 0; i < lists.size(); i++) {
                listString.add(lists.get(i));
            }
        }

        @Override
        public View createView(Context context) {
            // 返回页面布局
            View view = LayoutInflater.from(context).inflate(R.layout.custom_mzb_bannar_news_view, null);
            mImageView = view.findViewById(R.id.rci_cover);
            rl_banner = view.findViewById(R.id.rl_banner);
            tv_label = view.findViewById(R.id.tv_label);
            tv_time = view.findViewById(R.id.tv_time);
            return view;
        }


        @Override
        public void onBind(final Context context, final int position, final CollageInfoEntity.DataBean.BannerListBean data) {
            GlideUtils.loadImage(context, data.cover, mImageView);
            tv_label.setText(data.title);
            tv_time.setText(TimeUtil.dealDateFormat(data.publishTime));
            rl_banner.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(context, ColumnDetailsActivity.class);
                    intent.putExtra("informationId", data.informationId);
                    context.startActivity(intent);
                }
            });

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EventBusEntity event) {
        switch (event.getMsg()) {
            case 99:
                page = 1;
                initData();
                break;
            default:
                break;
        }
    }
}
